package ctm.javacode;

import java.io.*;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import java.lang.*;

import com.mysql.jdbc.StringUtils;

@WebServlet("/cuisine.do")
public class cuisine extends HttpServlet {
	
	/****** 資料庫變數 ******/
	String sqlQuery = "";
	ResultSet rs;
	
	/****** 禁忌食物食材******/
	ArrayList<ArrayList<String>> whole_grain_NotSuit = new ArrayList<ArrayList<String>>(); // 全穀根莖類
	ArrayList<ArrayList<String>> meat_NotSuit = new ArrayList<ArrayList<String>>(); // 豆魚肉蛋類
	ArrayList<ArrayList<String>> fat_NotSuit = new ArrayList<ArrayList<String>>(); // 油脂及堅果種子類
	ArrayList<ArrayList<String>> milk_NotSuit = new ArrayList<ArrayList<String>>(); // 低脂奶類
	ArrayList<ArrayList<String>> fruit_NotSuit = new ArrayList<ArrayList<String>>(); // 水果類
	ArrayList<ArrayList<String>> vegetables_NotSuit = new ArrayList<ArrayList<String>>(); // 蔬菜類
	ArrayList<ArrayList<String>> other_NotSuit = new ArrayList<ArrayList<String>>(); // 其他類
	
	/****** 可用食物食材******/
	ArrayList<ArrayList<String>> whole_grain_Suit = new ArrayList<ArrayList<String>>(); // 全穀根莖類
	ArrayList<ArrayList<String>> meat_Suit = new ArrayList<ArrayList<String>>(); // 豆魚肉蛋類
	ArrayList<ArrayList<String>> fat_Suit = new ArrayList<ArrayList<String>>(); // 油脂及堅果種子類
	ArrayList<ArrayList<String>> milk_Suit = new ArrayList<ArrayList<String>>(); // 低脂奶類
	ArrayList<ArrayList<String>> fruit_Suit = new ArrayList<ArrayList<String>>(); // 水果類
	ArrayList<ArrayList<String>> vegetables_Suit = new ArrayList<ArrayList<String>>(); // 蔬菜類
	ArrayList<ArrayList<String>> other_Suit = new ArrayList<ArrayList<String>>(); // 其他類
	
	/****** 食譜 ******/
	String ingredient = ""; //食材
	String seasoner =""; //調味料
	ArrayList<String> cuisine = new ArrayList<String>(); //食譜名稱
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		/****** 設定 ******/
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		dbBean db = new dbBean();
		db.setDataSource("jdbc/ctmpllab");
		db.Connected();
		PrintWriter out = response.getWriter();// Write the response back to the browser
			
		HttpSession session = request.getSession();

		String ac;
		if (request.isUserInRole("admin") || request.isUserInRole("professional") ){				
			ac = (String) session.getAttribute("login")+";nopersonId"; //nopersonId為未輸入身分證字號
		}else{
			ac = (String) session.getAttribute("login");
		}
		
		
		String input = request.getParameter("input");
		String type = request.getParameter("type");
		
		/****** 取得可用食物食材******/
		classificationfood _classificationfood = new classificationfood(ac);		
		/*whole_grain_Suit = _classificationfood.getsuitfood("全穀根莖類");
		meat_Suit = _classificationfood.getsuitfood("豆魚肉蛋類");
		fat_Suit = _classificationfood.getsuitfood("油脂及堅果種子類");
		milk_Suit = _classificationfood.getsuitfood("低脂奶類");
		fruit_Suit = _classificationfood.getsuitfood("水果類");
		vegetables_Suit = _classificationfood.getsuitfood("蔬菜類");
		other_Suit = _classificationfood.getsuitfood("其他類");
		*/
		/****** 取得禁忌食物食材******/
		whole_grain_NotSuit = _classificationfood.getnotsuitfood("全穀根莖類");
		meat_NotSuit = _classificationfood.getnotsuitfood("豆魚肉蛋類");
		fat_NotSuit = _classificationfood.getnotsuitfood("油脂及堅果種子類");
		milk_NotSuit = _classificationfood.getnotsuitfood("低脂奶類");
		fruit_NotSuit = _classificationfood.getnotsuitfood("水果類");
		vegetables_NotSuit = _classificationfood.getnotsuitfood("蔬菜類");
		other_NotSuit = _classificationfood.getnotsuitfood("其他類");
		

		
		/****** 食譜 ******/
		ingredient = ""; //食材
		seasoner =""; //調味料
		cuisine = new ArrayList<String>(); //食譜名稱
		
		switch (type) {
			case "join":
			
			try {			
				if (whole_grain_NotSuit.get(1).contains(input) || meat_NotSuit.get(1).contains(input) 
				|| fat_NotSuit.get(1).contains(input) || milk_NotSuit.get(1).contains(input) 
				|| fruit_NotSuit.get(1).contains(input) || vegetables_NotSuit.get(1).contains(input) 
				|| other_NotSuit.get(1).contains(input)){
					/****** 輸入食材為禁忌食物******/
					out.print("taboo");
				}else{
					out.print(input);
				}
				db.CloseConn();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		
		case "submit":
			
			String typeeat = request.getParameter("typeeat"); //選擇飲食型態
			try {
				if (input.contains("、")){
					String[] inputs = input.split("、");
					for (String each_input : inputs) {
						Searchcuisine(db,each_input,typeeat);
					}
				}else{
					Searchcuisine(db,input,typeeat);					
				}
							
				System.out.print("食譜"+cuisine.toString()+"\n");
				for (String _cuisine : cuisine){
					out.print("<option value='"+_cuisine+"'>");
					out.print(_cuisine);
					out.print("</option>");
				}
				
				db.CloseConn();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case "cuisine_list":
			sqlQuery = "SELECT * FROM `cuisinetable` WHERE cuisinename =" + "'"+ input + "'";
			System.out.print(sqlQuery+"\n");
			try {
				
				rs = db.ExcuteQuery(sqlQuery);				
				rs.next();
				
				/****** 食材材料******/
				out.print("<span>"+rs.getString("ingredientweigh")+"</span>"+",");
				
				/****** 調味料******/
				if (rs.getString("seasoner").equals("")){
					out.print("<span>無</span>"+",");
				}else{
					out.print("<span>"+rs.getString("seasonerweigh")+"</span>"+",");
				}
				
				/****** 作法******/
				String[] spilt_str = rs.getString("make").split("。");
				String make_str = "";
				for (int i=0;i<spilt_str.length;i++){
					if (i == spilt_str.length-1){
						make_str = make_str + "<span>"+ spilt_str[i] + "</span>";
					}else{
						make_str = make_str + "<span>"+ spilt_str[i] + "</span><br>";
					}
				}			
				out.print(make_str);
				
				/****** 網站*****/
				String website_str = rs.getString("website");
				if (!website_str.equals("")){
					out.print(","+"<span>影片來源：</span><a target=\"_new\" href="+"\""+website_str+"\">"+"現代心素派名人廚房"+"</a>");
				}else{
					out.print(","+website_str);
				}
				db.CloseConn();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;	
		}
					
		out.close();
	}
	
	private void Searchcuisine(dbBean db, String each_input, String typeeat) {
		// TODO Auto-generated method stub
		String type = "";
		if (typeeat.equals("vegetable"))
			type = "素";
		else if(typeeat.equals("meat"))
			type = "葷";
		else
			type = "葷素都可";
		
		try {
			if (type.equals("葷素都可"))
				sqlQuery = "SELECT * FROM `cuisinetable` WHERE ingredient LIKE '%"+each_input+"%' or seasoner LIKE '%"+each_input+"%'";
			else				
				sqlQuery = "SELECT * FROM `cuisinetable` WHERE ingredient LIKE '%"+each_input+"%' && type='"+type+ "'or seasoner LIKE '%"+each_input+"%' && type='"+type+"'";
			rs = db.ExcuteQuery(sqlQuery);
			while (rs.next()) {
				ingredient = rs.getString("ingredient");
				seasoner = rs.getString("seasoner");
				String all_ingredient = "";
				if (seasoner.equals("")){
					all_ingredient = ingredient;
				}else{
					all_ingredient = ingredient + "、" + seasoner;
				}
				cuisine = filter(cuisine,all_ingredient);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private ArrayList<String> filter(ArrayList<String> cuisinelist,String food) {
		boolean joincuisine = true;
		ArrayList<String> cuisine = cuisinelist; //食譜名稱
		try{
			if (food.contains("、")){
				String[] foodlist = food.split("、");
				for (String temp : foodlist) {			
					if (whole_grain_NotSuit.get(1).contains(temp) || meat_NotSuit.get(1).contains(temp) 
					|| fat_NotSuit.get(1).contains(temp) || milk_NotSuit.get(1).contains(temp) 
					|| fruit_NotSuit.get(1).contains(temp) || vegetables_NotSuit.get(1).contains(temp) 
					|| other_NotSuit.get(1).contains(temp)){
						joincuisine = false;
						//System.out.print("join: "+joincuisine+" ; temp: "+temp+"\n");
						break;
					}/*else{
						if (whole_grain_Suit.get(1).contains(temp) || meat_Suit.get(1).contains(temp) 
								|| fat_Suit.get(1).contains(temp) || milk_Suit.get(1).contains(temp) 
								|| fruit_Suit.get(1).contains(temp) || vegetables_Suit.get(1).contains(temp) 
								|| other_Suit.get(1).contains(temp) ){								
							joincuisine = true;
						} else {
							joincuisine = false;
							System.out.print("join: "+joincuisine+" ; temp: "+temp+"\n");
							break;
						}
					}*/
					//System.out.print("join: "+joincuisine+" ; temp: "+temp+"\n");
				}
			}
			if(joincuisine){
				if (!cuisine.contains(rs.getString("cuisinename")))
					cuisine.add(rs.getString("cuisinename"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return cuisine;		
	}

}
